import { world, BlockVolume, Player } from "@minecraft/server";
import { LandList } from '../core/data/land/LandList'

const filledChunks = new Set();

// 地皮布局常量
const START_X = 16;                         // 起始坐标X
const START_Z = 16;                         // 起始坐标Z
const PLOT_SIZE = 144;                      // 地皮尺寸（144方块）
const PLOT_GAP = 16;                        // 地皮间隔（16方块）
const TOTAL_STEP = PLOT_SIZE + PLOT_GAP;    // 总步长160方块


/**
 * @param {number} x
 * @param {number} z
 */
export function get_chunk_diagon_position(x, z) {
    const chunkX = Math.floor(x / 16) * 16;
    const chunkZ = Math.floor(z / 16) * 16;

    return {
        x: chunkX,
        z: chunkZ
    }
}


/**
 * @param {number} chunkX
 * @param {number} chunkZ
 */
export function fill_chunk_blcoks(chunkX, chunkZ) {
    const chunkKey = `${chunkX},${chunkZ}`;

    if (!filledChunks.has(chunkKey)) {
        const overworld = world.getDimension("overworld");

        const volume_black_concrete = new BlockVolume(
            { x: chunkX, y: 100, z: chunkZ },
            { x: chunkX + 15, y: 100, z: chunkZ + 15 }
        );

        const volume_quartz_block = new BlockVolume(
            { x: chunkX + 1, y: 100, z: chunkZ + 1 },
            { x: chunkX + 14, y: 100, z: chunkZ + 14 }
        );

        const volume_lime_concrete = new BlockVolume(
            { x: chunkX + 7, y: 100, z: chunkZ + 7 },
            { x: chunkX + 8, y: 100, z: chunkZ + 8 }
        );

        try {
            overworld.fillBlocks(volume_black_concrete, "minecraft:black_concrete");
            overworld.fillBlocks(volume_quartz_block, "minecraft:quartz_block");
            overworld.fillBlocks(volume_lime_concrete, "minecraft:lime_concrete");
            filledChunks.add(chunkKey);
        } catch (e) {
            if (String(e).includes("unloaded chunk")) return;
            throw e;
        }
    }
}


/**
 * @param {number} x
 * @param {number} z
 */
export function is_in_rect_area(x, z) {
    const RECT_SIZE = 144;
    const GAP = 16;
    const STEP = RECT_SIZE + GAP;

    const startX = 16;
    const startZ = 16;

    const gridX = Math.floor((x - startX) / STEP);
    const gridZ = Math.floor((z - startZ) / STEP);

    const rectStartX = startX + gridX * STEP;
    const rectStartZ = startZ + gridZ * STEP;
    const rectEndX = rectStartX + RECT_SIZE;
    const rectEndZ = rectStartZ + RECT_SIZE;

    return (x >= rectStartX && x <= rectEndX &&
        z >= rectStartZ && z <= rectEndZ);
}


/**
 * @param {number} count
 * @returns { {min: {x: number,z: number}, max: {x: number,z: number}, center: { x: number, z: number}}[] }
 */
export function get_plot_array(count) {
    const plots = [];

    // 基准点
    const gridStartX = START_X;
    const gridStartZ = START_Z;

    // 生成所有地皮位置
    for (let i = 0; i < count; i++) {
        for (let j = 0; j < count; j++) {
            // 计算当前地皮左下角坐标
            const minX = gridStartX + j * TOTAL_STEP;
            const minZ = gridStartZ + i * TOTAL_STEP;

            // 计算右上角坐标
            const maxX = minX + PLOT_SIZE;
            const maxZ = minZ + PLOT_SIZE;

            // 计算中心点
            const centerX = minX + PLOT_SIZE / 2;
            const centerZ = minZ + PLOT_SIZE / 2;

            // 返回数据
            plots.push({
                min: { x: minX, z: minZ },
                max: { x: maxX, z: maxZ },
                center: { x: centerX, z: centerZ }
            });
        }
    }

    return plots;
};


/**
 * 将任意坐标转换为所在地皮的边界坐标
 * @param {number} x X坐标
 * @param {number} z Z坐标
 * @returns { area: {{min: {x: number, z: number}, max: {x: number, z: number}}, center: {x: number, z: number}} | null }
 */
export function convertToPlotCoordinates(x, z) {
    // 计算坐标所在的地皮网格位置
    const gridX = Math.floor((x - START_X) / TOTAL_STEP);
    const gridZ = Math.floor((z - START_Z) / TOTAL_STEP);

    // 计算地皮左下角坐标
    const minX = START_X + gridX * TOTAL_STEP;
    const minZ = START_Z + gridZ * TOTAL_STEP;

    // 计算地皮右上角坐标
    const maxX = minX + PLOT_SIZE;
    const maxZ = minZ + PLOT_SIZE;

    // 计算中心点坐标
    const centerX = minX + PLOT_SIZE / 2;
    const centerZ = minZ + PLOT_SIZE / 2;

    return {
        area: {
            min: { x: minX, z: minZ },
            max: { x: maxX, z: maxZ }
        },
        center: { x: centerX, z: centerZ }
    };
};

/**
 * @param { Player } player
 * @param { LandList } land_list
 */
export function receive_land(player, land_list) {
    // 获取当前玩家用户名
    const playerId = player.name;

    // 获取所有地块数据
    const rawLandData = land_list.get_all_plot_data();
    const land_data_list = rawLandData ? JSON.parse(rawLandData) : [];

    // 检查玩家是否已拥有领地
    const hasLand = land_data_list.some(plot =>
        plot.admin === playerId
    );

    if (hasLand) {
        player.onScreenDisplay.setTitle("您已拥有领地，不能重复领取！");
        return;  // 终止执行
    }

    // 计算新地块索引
    const newIndex = land_data_list.length;

    // 获取包含新地块的完整地块列表
    const land_utils_list = get_plot_array(newIndex + 1);
    const newLand = land_utils_list[newIndex];

    // 添加地块时记录玩家信息
    land_list.app_end_data_list(
        player,
        {
            min: newLand.min,
            max: newLand.max,
        },
        newIndex
    );

    // 传送玩家
    player.teleport({
        x: newLand.center.x,
        y: 101,
        z: newLand.center.z
    });
}